import 'package:book_manager_app/app/modules/add_book/models/add_book_req.dart';
import 'package:book_manager_app/app/modules/add_book/models/book_package_info.dart';
import 'package:book_manager_app/app/modules/add_book/models/book_sales_req.dart';
import 'package:http_manager/http_manager.dart';
import 'package:book_manager_app/app/modules/add_book/models/book.dart';
import 'package:dio/dio.dart';
import 'package:http_manager/logger.dart';
import '../../../../host.dart';
import '../../../utils/common/app_manager.dart';

class BookRequest {

  /// 新增图书
  /// {"referencePrice":"1","purchasePrice":"1","salePrice":"1","discountPrice":"1","storeId":"695236584013885524"}
  static Future<ResponseAnalyzed> addBook(AddBookReq book) async {
    const url = "/api/bookstore/store/book";
    var response = await HttpManager.post(url, params: book.toJson());
    return await ResponseAnalyzed.analyzingAndCheckup(response);
  }


  // 更新图书信息、包括图书的库存信息
  static Future<ResponseAnalyzed> addStock(AddBookReq book) async {
    // const url = "/api/bookstore/store/book/update";
    const url = "/api/bookstore/store/book/addStock";
    final param = {
      "storeId": book.storeId,
      "bookId": book.id,
      "quantity": book.inventory ?? 0,
    };
    return HttpManager.postAnalyzing(url, params: param);
  }

  /// 通过、书名、书号 isbn 获取图书的信息（本地服务器）
  static Future<ResponseAnalyzed> getBookInfo(String isbn) async {
    final param = {"isbn": isbn};
    return HttpManager.getAnalyzing("/api/bookstore/store/book", params: param);
  }

  /// 通过二维码总的 packageId 获取套装的信息（本地服务器）
  // api/bookstore/store/package
  static Future<ResponseAnalyzed> getPackageInfo(String packageId) async {
    return HttpManager.getAnalyzing("/api/bookstore/store/package/$packageId");
  }

  /// 单本出售
  /// 赠送
  /// {storeId: 2, bookId: "715660549605556464", isbn: "9787549128785", quantity: 1, payType: 5}
  static Future<ResponseAnalyzed> sale(BookSalesReq req) async {
    const url = "/api/bookstore/store/book/sales";
    final param = req.toJson();
    try {
      return HttpManager.postAnalyzing(url, params: param);
    } catch (e) {
      return ResponseAnalyzed(
        code: "500",
        message: "出库失败",
        data: null
      );
    }
  }

  /// 套装出售
  static Future<ResponseAnalyzed> salePackage(BookSalesReq req) async {
    const url = "/api/bookstore/store/package/sales";
    final param = req.toJson();
    try {
      return HttpManager.postAnalyzing(url, params: param);
    } catch (e) {
      return ResponseAnalyzed(
        code: "500",
        message: "出库失败",
        data: null
      );
    }
  }

  /// 通过书号 isbn 获取图书的信息（第三方渠道）
  /// 681ef544b8403d7929b7acb6e3df31c6  wangliqi
  static Future<ResponseAnalyzed> tanshuapi(var isbn) async {
    // 创建一个独立的dio实例，避免影响全局HttpManager
    final dio = Dio();
    const baseUrl = "http://api.tanshuapi.com";
    const key = "374eecfa901489387da53e78f4786ddc";
    final url = "$baseUrl/api/isbn/v1/index?key=$key&isbn=$isbn";
    // 发送GET请求
    final startTime = DateTime.now();
    final response = await dio.get(url);
    final endTime = DateTime.now();
    Logger.debug(
      url: url,
      httpMethod: 'GET',
      requestParams: {'isbn': isbn, 'key': key},
      operationType: '第三方API请求',
      startTime: startTime.toString(),
      endTime: endTime.toString(),
      responseData: response,
    );
    // 构建与原方法相同的返回结果格式
    final result = ResponseAnalyzed(
      code: response.data['code'].toString(),
      message: response.data['msg'] ?? '',
      data: response.data['data']
    );
    return result;
  }


}